<?php $this->load->view("include/meta"); ?> 
    <title><?php echo TITLE;?></title>

    <!-- Bootstrap core CSS -->
    <link href="<?php echo site_url();?>assets/css/bootstrap.css" rel="stylesheet">
    <link href="<?php echo site_url();?>assets/css/common.css" rel="stylesheet">

  </head>

  <body>

    <!-- Wrap all page content here -->
    <div id="wrap"> 

    <!-- header start -->
    <?php $this->load->view("include/header"); ?> 
    <!-- header end -->

    <!-- main start -->
    <div class="container"  style="width:100%;" id="main">
        <!-- row 1 -->
        <div class="row">
            <!-- baidu map -->
            <div id="map_container" >
            </div>

        </div>  <!-- end row -->

    </div>    <!-- end content -->
    <!-- main end -->

    </div>      
    <!-- Wrap end -->

    <!-- footer start -->
    <?php $this->load->view("include/footer"); ?> 
    <!-- footer end -->

    <script type="text/javascript" src="<?php echo site_url();?>assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="<?php echo site_url();?>assets/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="<?php echo site_url();?>assets/js/jquery.cookie.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=<?php echo BAIDU_AK;?>"></script>
    <script type="text/javascript" src="<?php echo site_url();?>assets/js/location.js"></script>
    <script>
            var fid = 0;
            var lastPosition = [0,0];
            var isMobile =<?php echo $isMobile;?>; 

            var default_city = '北京市';
            var city ='<?php echo $city ? $city :'';?>';

            //map start
            var map = new BMap.Map("map_container",{enableMapClick:false});  
            map.centerAndZoom(city ? city : default_city,13); 
            map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_SMALL})); 
            map.enableDragging();

            setSizes();

            map.addEventListener("tilesloaded",function()
            {
                if(!$.cookie('city'))
                {
                    var myCity = new BMap.LocalCity();
                    myCity.get(map_reload);
                }

                //手机使用非WIFI，用网络定位可能会有问题，GPS重新定位
                if( ( isMobile && ( !$.cookie('gpstime') || parseInt( new Date().getTime() / 1000 ) > $.cookie('gpstime')) && navigator.geolocation ) )
                {
                    navigator.geolocation.getCurrentPosition(
                    getCityByGEO,
                    GEOError,
                    {enableHighAcuracy: true}
                    );
                }

                showInfo();
            });

            //拖动后事件
            map.addEventListener("dragend", showInfo); 


            //common map function
            function showInfo()
            {
                var cp = map.getCenter();

                //检查位置是否有变动
                if(cp.lng == lastPosition[0] && cp.lat == lastPosition[1])
                {
                    return false;
                }
                else
                {
                    //标记最后的位置，避免重复提交
                    lastPosition = [cp.lng,cp.lat];
                }

                var cityid = getCityId();

                $.ajax({
                    url: "<?php echo site_url();?>api/activity/getNearby",
                    type: "GET",
                    dataType: "json",
                    data: "lat="+cp.lat+"&lng="+cp.lng+"&cityid="+cityid+"&fid="+fid,
                    success: function(data){

                        if(data.error == 0)
                        {
                            //清除原来的
                            map.clearOverlays();

                            for(i in data.data)
                            {
                                //添加标记
                                var point = new BMap.Point(data.data[i]['longitude'],data.data[i]['latitude']);
                                var myIcon = new BMap.Icon("<?php echo site_url();?>assets/images/icons/32/"+data.data[i]['fid']+".png",new BMap.Size(32,32));
                                var marker = new BMap.Marker(point,{icon:myIcon});
                                map.addOverlay(marker);

                                //添加信息窗口
                                var opts = {
                                  enableMessage:false,
                                }

                                var playtime = data.data[i]['playtime'];
                                    playtime = playtime.substr(0,playtime.length-3);

                                var infoContent= "<p><img src='<?php echo site_url();?>assets/images/icons/16/"+data.data[i]['fid']+".png' /> "+data.data[i]['subject']+" <a target='_blank' href='<?php echo site_url();?>activity/?tid="+data.data[i]['tid']+"'>详情>></a></p><p>发起人：<a href='<?php echo site_url('user').'/?uid=';?>"+data.data[i]['authorid']+"' target='_blank'>"+data.data[i]['username']+"</a></p><p>活动时间："+playtime+"</p>";

                                if(data.data[i]['apply_num'] > 0)
                                {
                                    infoContent += '<p>已有<span>'+data.data[i]['apply_num']+'</span>人报名</p>';
                                }

                                marker.infoWindow = new BMap.InfoWindow(infoContent,opts);
                                marker.addEventListener("click", function(e){this.openInfoWindow(e.target.infoWindow);});
                            }
                        }
                    }   
                }); 

            }

            function map_reload(result)
            {
                //网络速度慢，第一次定位失败，这里补充定位
                var cityName = result.name;

                if(cityName) 
                {
                    map.centerAndZoom(cityName,13); 
                    $.cookie('city', cityName,{ expires: 3, path: '/' });
                    city = result.name;
                }

            }

            function getCityId()
            {
                var last = city.substr(-1);

                if(last == '市')
                {
                    city = city.substr(0,city.length-1);
                }

                return cityIds[city];
            }

            //map end 

            //定位
            function getCityByGEO(pos)
            {
                var lat = pos.coords.latitude;
                var lng = pos.coords.longitude;
                var url = 'http://api.map.baidu.com/geocoder/v2/?ak=<?php echo BAIDU_AK;?>&callback=GEOCallback&location='+lat+','+lng+'&output=json&pois=0';

                var script = document.createElement('script');
                    script.type = 'text/javascript';
                    script.src=url;
                    document.body.appendChild(script);
            }

            //GPS定位的回调
            function GEOCallback(response) 
            {
                if(response.status === 0)
                {
                    var GPSCity = response.result.addressComponent.city;
                    var cookieCity = $.cookie('city');

                    if(GPSCity != cookieCity)
                    {
                        //或许某天需要setTimeout
                        map.centerAndZoom(GPSCity,13); 
                        $.cookie('city', GPSCity,{ expires: 3, path: '/' });
                        city=GPSCity;
                    }

                    $.cookie('gpstime', parseInt(new Date().getTime() / 1000) + 1800,{ expires: 3, path: '/' });
                }
            }
            
            function GEOError()
            {
                return false;
            }
            //定位end


            //common function
            function setSizes() {
                $('#map_container').height($(window).height() - $("#header").height() - $('#footer').height() );
                $('#map_container').width($(window).width());
            }

    </script>
    </body>
</html>
